<?php

namespace backend\widgets;
use Yii;
use yii\base\InvalidConfigException;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use Symfony\Component\Finder\Finder;

class ExportMenu extends \kartik\export\ExportMenu
{

    public $minCount;
    public $customPath;
    public $_exportType;


    public function init()
    {
        parent::init();
    }

    public function run()
    {

        if(Yii::$app->request->isPost){

            if(!isset($_POST['export_type'])){
                return parent::run();
            }
            if (!function_exists("fastcgi_finish_request")) {
                return parent::run();
            }

            if(($this->minCount != null) && ($this->minCount <$this->dataProvider->getTotalCount())){

              //  echo Yii::$app->response->redirect(Url::current());
               $isCn = Yii::$app->language == 'zh-CN' ? true : false;

               if($isCn){
                   $title = '文件将显示在列表页';
                   $content = '您要导出的文件过大，处理需要些时间，请耐心等候！</p><p>导出的文件稍后会显示在您访问的列表页。';

               }else{
                   $title ='Файл будет показан на странице вы посмотрели.';
                   $content = 'Из-за большого объема данных, подождите пожалуйста для выгрузки файла.';
               }
                echo '<title>'.$title.'</title><div class="load_text"><div class="all_content"><img style="width:400px;display: table-cell;margin-right:20px;" src="/resources/dist/img/fileloading.jpg"> <div style="display: table-cell;vertical-align: middle;"><p class="tit">'.$content.'</p></div></div></div> <style>.load_text{position: fixed;width:100%;top:50%;-webkit-transform: translateY(-50%);transform: translateY(-50%);}.all_content{display: table;margin: 0 auto;}.choose_page,.download_file{display: none}.tit{font-weight: bold}</style>';

                fastcgi_finish_request();
                set_time_limit(0);
                ini_set('memory_limit','-1');

                $this->initI18N(__DIR__);
                $this->initColumnSelector();
                $this->setVisibleColumns();
                $this->initExport();
                if($this->customPath != null){
                    $this->folder = $this->folder.'/'.Yii::$app->user->id.'/'.$this->customPath;
                }else{
                    $this->folder = $this->folder.'/'.Yii::$app->user->id.'/'.Yii::$app->controller->getRoute();
                }
                $request = Yii::$app->request;
                $this->_exportType = $request->post($this->exportTypeParam, $this->exportType);
                $config = ArrayHelper::getValue($this->exportConfig, $this->_exportType, []);
                if (empty($config['writer'])) {
                    throw new InvalidConfigException(
                        "The 'writer' setting for '\PhpOffice\PhpSpreadsheet\Spreadsheet' must be setup in 'exportConfig'."
                    );
                }
                $this->initPhpSpreadsheet();
                $this->initPhpSpreadsheetWriter($config['writer']);
                $this->initPhpSpreadsheetWorksheet();
                $this->generateBeforeContent();
                $this->generateHeader();
                $this->generateBody();
                if (!empty($this->dataValidation)) {
                    foreach ($this->dataValidation as $sheetName => $validations) {
                        foreach ($validations as $cell => $length) {
                            $this->setDataValidation($sheetName, $cell, $length);
                        }
                    }
                }
                if (!empty($this->supplementSheets)) {
                    $this->createSupplementSheets();
                }
                $this->_objSpreadsheet->setActiveSheetIndex(0)->setTitle($this->sheetName);
                $row = $this->generateFooter();
                $this->generateAfterContent($row);
                $writer = $this->_objWriter;
                $sheet = $this->_objWorksheet;
                if ($this->autoWidth) {
                    foreach ($this->getVisibleColumns() as $n => $column) {
                        $sheet->getColumnDimension(self::columnName($n + 1))->setAutoSize(true);
                    }
                }
                $this->raiseEvent('onRenderSheet', [$sheet, $this]);
                $this->folder = trim(Yii::getAlias($this->folder));


                if (!file_exists($this->folder) && !mkdir($this->folder, 0777, true)) {
                    throw new InvalidConfigException(
                        "Invalid permissions to write to '{$this->folder}' as set in `ExportMenu::folder` property."
                    );
                }
                //echo mb_convert_encoding($this->filename,"GBK","UTF-8");die;
                $filename =   iconv("UTF-8", "ISO-8859-1//TRANSLIT", $this->filename);

                $file = self::slash($this->folder) . $filename . '.' . $config['extension'];
                $writer->save($file);
            }
        }

        return parent::run(); // TODO: Change the autogenerated stub
    }
}
